//
// Created by lenovo on 2024/9/11.
//

#include "LiveService.h"
#include "ZYUtils/ZYLog.h"

namespace ZYLive{
    LiveService::LiveService() {

    }

    LiveService::~LiveService(){
        if(mServer != nullptr)
            mServer.reset();

    }

    void LiveService::setPushInfo(std::string url)
    {
        mUrl = url;
        initServer();
    }


    std::string LiveService::getUrl()
    {
        std::string url = std::string();
        if(mServer){
            url = mServer->getLiveUrl();
        }
        return url;
    }
    
    bool LiveService::initServer() {
        if(mServer){
            mServer.reset();
            mServer = nullptr;
        }

        if(mUrl.empty()){
            ZYUtils::ZY_LOG("url is nullptr");
            return false;
        }
        
        // 修复：为LiveServer提供必需的目录参数
        std::string configDir = "/tmp/zlmediakit_config"; // 使用临时目录作为配置目录
        mServer = std::make_shared<LiveServer>(configDir);

        mPushType = 1;
        if(mUrl.find("rtmp") != std::string::npos){
            mPushType = 0;
        }
        mServer->createMediaPlayer("live/0",(mPushType == 0));

        return true;
    }
    
    bool LiveService::createPusher(int &width,int &height,int &fps,float &bitrate)
    {
        auto url = mServer->getLiveUrl();
        if(url.empty()){
            ZYUtils::ZY_LOG("url is nullptr,server is error!");
            return false;
        }


        if(mPusher){
            mPusher.reset();
            mPusher = nullptr;
        }

        mPusher = std::make_shared<ZYLive::FFMpegPusher>(width,height,fps,bitrate,url);
        return true;
    }

    bool LiveService::setVideoInfo(int width, int height, int fps, float bitrate) {
        if(mServer == nullptr){
            initServer();
        }

        auto flag = (mWidth != width || mHeight != height || mFps != fps || mBitRate != bitrate);
        if( flag || mPusher == nullptr ){
            createPusher(width,height,fps,bitrate);

            mIsInitPusher = true;


            mWidth = width;
            mHeight = height;
            mFps = fps;
            mBitRate = bitrate;
        }

        return true;

    }

    int  LiveService::pushVideoData(uint8_t *pData, int format,int width,int height) {
        if(mIsInitPusher == false){
            createPusher(mWidth,mHeight,mFps,mBitRate);
        }

        return mPusher->pushData(pData,format,width,height);
    }


}